package com.beijiteshop.shop.ui.address.vm

import androidx.lifecycle.MutableLiveData
import com.beijiteshop.libcommon.base.viewmodel.BaseViewModel
import com.beijiteshop.libcommon.network.ext.*
import com.beijiteshop.libcommon.network.model.onFailure
import com.beijiteshop.libcommon.network.model.onSuccess
import com.beijiteshop.shop.model.api.response.AddressBean
import com.beijiteshop.shop.ui.address.repo.AddressRepo

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/9 19:39
 * @Description
 */
class AddressVM(private val repo: AddressRepo) : BaseViewModel() {

    val liveAddressList = MutableLiveData<List<AddressBean>>()

    val liveAddAddress = MutableLiveData<String?>()

    val liveUpdateAddress = MutableLiveData<String?>()

    val liveDeleteAddress = MutableLiveData<String?>()

    fun getAddressList() = launch {
        repo.getAddressList()
            .serverData()
            .onSuccess {
                onBizOK { code, data, message ->
                    if (data.isNullOrEmpty()){
                        liveEmpty.postValue(null)
                    }else{
                        liveAddressList.postValue(data)
                    }
                }

                onBizError { code, message ->
                    liveError.postValue(message)
                }

                onBizEmpty {
                    liveEmpty.postValue(it)
                }
            }
            .onFailure {
                liveNetError.postValue(it.message)
            }
    }

    fun addAddress(addressBean: AddressBean) = launch {
        repo.addAddress(addressBean)
            .serverData()
            .onSuccess {
                onBizOk { msg, data ->
                    liveAddAddress.postValue(msg)
                }

                onBizError { code, msg ->
                    liveError.postValue(msg)
                }
            }.onFailure {
                liveNetError.postValue(it.message)
            }
    }

    fun updateAddress(addressBean: AddressBean) = launch {
        repo.updateAddress(addressBean)
            .serverData()
            .onSuccess {
                onBizOk {msg,data->
                    liveUpdateAddress.postValue(msg)
                }

                onBizError { code, msg ->
                    liveError.postValue(msg)
                }
            }.onFailure {
                liveNetError.postValue(it.message)
            }
    }

    fun deleteAddress(id: String) = launch {
        repo.deleteAddress(id)
            .serverData()
            .onSuccess {
                onBizOk {msg,data->
                    liveDeleteAddress.postValue(msg)
                }

                onBizError { code, msg ->
                    liveError.postValue(msg)
                }
            }.onFailure {
                liveNetError.postValue(it.message)
            }
    }
}